class BaiduMap_ extends ol.source.TileImage {
  constructor(opt_options) {
    var options = opt_options || {};
    var attributions =
      options.attributions ||
      "Map Data © 2018 Baidu - GS(2016)2089号 - Data © 长地万方 with <span>© SuperMap iClient</span>";
    var tileGrid = BaiduMap_.defaultTileGrid();
    var crossOrigin = options.crossOrigin !== undefined ? options.crossOrigin : 'anonymous';

    var url =
      options.url !== undefined
        ? options.url
        : 'https://maponline{num}.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}&styles={styles}&udt=20170408';
    var hidpi =
      options.hidpi || (window.devicePixelRatio || window.screen.deviceXDPI / window.screen.logicalXDPI) > 1;
    url = url.replace('{styles}', hidpi ? 'ph' : 'pl');
    super({
      attributions: attributions,
      cacheSize: options.cacheSize,
      crossOrigin: crossOrigin,
      opaque: options.opaque !== undefined ? options.opaque : true,
      maxZoom: options.maxZoom !== undefined ? options.maxZoom : 19,
      reprojectionErrorThreshold: options.reprojectionErrorThreshold,
      tileLoadFunction: options.tileLoadFunction,
      projection: 'EPSG:3857',
      wrapX: options.wrapX,
      tilePixelRatio: hidpi ? 2 : 1,
      tileGrid: tileGrid,
      tileUrlFunction: tileUrlFunction
    });

    if (options.tileProxy) {
      this.tileProxy = options.tileProxy;
    }
    var me = this;

    // eslint-disable-next-line no-unused-vars
    function tileUrlFunction(tileCoord, pixelRatio, projection) {
      var tempUrl = url
        .replace('{num}', Math.abs((tileCoord[1] + tileCoord[2]) % 4))
        .replace('{z}', tileCoord[0].toString())
        .replace('{x}', tileCoord[1].toString())
        .replace('{y}', function () {
          var y = -tileCoord[2] - 1;
          return y.toString();
        })
        .replace('{-y}', function () {
          var z = tileCoord[0];
          var range = tileGrid.getFullTileRange(z);
          external_ol_asserts_namespaceObject.assert(range, 55); // The {-y} placeholder requires a tile grid with extent
          var y = range.getHeight() + tileCoord[2];
          return y.toString();
        });

      //支持代理
      if (me.tileProxy) {
        tempUrl = me.tileProxy + encodeURIComponent(tempUrl);
      }
      return tempUrl;
    }
  }

  // TODO 确认这个方法是否要开出去
  /**
   * @function BaiduMap.defaultTileGrid
   * @description 获取默认瓦片格网。
   * @returns {ol.tilegrid.TileGrid} 返回瓦片格网对象。
   */
  static defaultTileGrid() {
    var tileGird = new ol.tilegrid.TileGrid({
      extent: [-33554432, -33554432, 33554432, 33554432],
      resolutions: [
        131072 * 2,
        131072,
        65536,
        32768,
        16284,
        8192,
        4096,
        2048,
        1024,
        512,
        256,
        128,
        64,
        32,
        16,
        8,
        4,
        2,
        1,
        0.5
      ],
      origin: [-1480, 24590],
      minZoom: 3
    });
    return tileGird;
  }
}
// https://blog.csdn.net/qq_36305530/article/details/132431669
const Projection = ol.proj.Projection;
const addProjection = ol.proj.addProjection;
const addCoordinateTransforms = ol.proj.addCoordinateTransforms;
const getTransform = ol.proj.getTransform;

const PI = Math.PI
const AXIS = 6378245.0
const OFFSET = 0.00669342162296594323 // (a^2 - b^2) / a^2

function delta(wgLon, wgLat) {
  let dLat = transformLat(wgLon - 105.0, wgLat - 35.0)
  let dLon = transformLon(wgLon - 105.0, wgLat - 35.0)
  const radLat = (wgLat / 180.0) * PI
  let magic = Math.sin(radLat)
  magic = 1 - OFFSET * magic * magic
  const sqrtMagic = Math.sqrt(magic)
  dLat = (dLat * 180.0) / (((AXIS * (1 - OFFSET)) / (magic * sqrtMagic)) * PI)
  dLon = (dLon * 180.0) / ((AXIS / sqrtMagic) * Math.cos(radLat) * PI)
  return [dLon, dLat]
}

function outOfChina(lon, lat) {
  if (lon < 72.004 || lon > 137.8347) {
    return true
  }
  if (lat < 0.8293 || lat > 55.8271) {
    return true
  }
  return false
}

function transformLat(x, y) {
  let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x))
  ret += ((20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0) / 3.0
  ret += ((20.0 * Math.sin(y * PI) + 40.0 * Math.sin((y / 3.0) * PI)) * 2.0) / 3.0
  ret += ((160.0 * Math.sin((y / 12.0) * PI) + 320 * Math.sin((y * PI) / 30.0)) * 2.0) / 3.0
  return ret
}

function transformLon(x, y) {
  let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x))
  ret += ((20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0) / 3.0
  ret += ((20.0 * Math.sin(x * PI) + 40.0 * Math.sin((x / 3.0) * PI)) * 2.0) / 3.0
  ret += ((150.0 * Math.sin((x / 12.0) * PI) + 300.0 * Math.sin((x / 30.0) * PI)) * 2.0) / 3.0
  return ret
}

const forEachPoint = function (func) {
  return function (input, opt_output, opt_dimension) {
    const len = input.length
    const dimension = opt_dimension || 2
    let output
    if (opt_output) {
      output = opt_output
    } else if (dimension !== 2) {
      output = input.slice()
    } else {
      output = new Array(len)
    }
    for (let offset = 0; offset < len; offset += dimension) {
      func(input, output, offset)
    }
    return output
  }
}

const gcj02 = {
  toWGS84: forEachPoint(function (input, output, offset) {
    let lng = input[offset]
    let lat = input[offset + 1]
    if (!outOfChina(lng, lat)) {
      const deltaD = delta(lng, lat)
      lng = lng - deltaD[0]
      lat = lat - deltaD[1]
    }
    output[offset] = lng
    output[offset + 1] = lat
  }),
  fromWGS84: forEachPoint(function (input, output, offset) {
    let lng = input[offset]
    let lat = input[offset + 1]
    if (!outOfChina(lng, lat)) {
      const deltaD = delta(lng, lat)
      lng = lng + deltaD[0]
      lat = lat + deltaD[1]
    }
    output[offset] = lng
    output[offset + 1] = lat
  }),
}

const projzh = {
  ll2smerc: getTransform('EPSG:4326', 'EPSG:3857'),
  smerc2ll: getTransform('EPSG:3857', 'EPSG:4326'),
}

// wgs84 -> gcj02
projzh.ll2gmerc = function (input, opt_output, opt_dimension) {
  const output = gcj02.fromWGS84(input, opt_output, opt_dimension)
  return projzh.ll2smerc(output, output, opt_dimension)
}
// gcj02 -> wgs84
projzh.gmerc2ll = function (input, opt_output, opt_dimension) {
  const output = projzh.smerc2ll(input, input, opt_dimension)
  return gcj02.toWGS84(output, opt_output, opt_dimension)
}
// 3857 -> gcj02
projzh.smerc2gmerc = function (input, opt_output, opt_dimension) {
  let output = projzh.smerc2ll(input, input, opt_dimension)
  output = gcj02.fromWGS84(output, output, opt_dimension)
  return projzh.ll2smerc(output, output, opt_dimension)
}
// gcj02 -> 3857
projzh.gmerc2smerc = function (input, opt_output, opt_dimension) {
  let output = projzh.smerc2ll(input, input, opt_dimension)
  output = gcj02.toWGS84(output, output, opt_dimension)
  return projzh.ll2smerc(output, output, opt_dimension)
}

// 定义GCJ02墨卡托投影坐标系
const gcj02Mecator = new Projection({
  code: 'GCJ-02',
  // extent不能缺少，OpenLayers frame 渲染的时候需要
  extent: [-20037508.342789244, -20037508.342789244, 20037508.342789244, 20037508.342789244],
  units: 'm',
})

// 将GCJ02墨卡托投影坐标系注册进OpenLayers
addProjection(gcj02Mecator)
// 覆盖默认的转换方法
addCoordinateTransforms('EPSG:4326', gcj02Mecator, projzh.ll2gmerc, projzh.gmerc2ll)
addCoordinateTransforms('EPSG:3857', gcj02Mecator, projzh.smerc2gmerc, projzh.gmerc2smerc)

export default {
  BaiduMap_: BaiduMap_,
  gcj02Mecator: gcj02Mecator
}